using System;
using System.Configuration;
using System.Net.Mail;
using System.Xml;
using umlungu.engineX.emailX;
using NashuaMobile;

//using log4net;

/*	-----------------------------------------------------------------------	
	Copyright:	umlungu consulting (pty) ltd
	Author:		Alan Benington
	Started:	2004-08-10
	Status:		dev
	Version:	0.0.1
	License:	GNU General Public License
	-----------------------------------------------------------------------	*/
	
namespace umlungu.engineX.workflowX {
	/// <summary>
	/// This class handles the notification messages that relate to work-items and tasks.
	/// <para>The target of notifications are typically users and agents</para>
	/// </summary>
	public class x_worknotify {
		#region Constants
		private const string error_email 	= "Error while sending an email notification.";
		private const string html_header	= "<html><body>";
		private const string html_footer	= "</body></html>";
		#endregion
		
		#region Invisible properties
		#endregion

		#region Visible properties
		private bool html = false;
		/// <summary>Indicates if message is to be sent as html</summary>
		/// <value>true if html, default is 'false'</value>
		
		//public static readonly ILog Logger = LogManager.GetLogger(typeof(x_worknotify));
		public bool Html {
			get { return html; }
			set { html = value; }
		}
		#endregion

		#region Constructors/Destructors
		/// <overloads>Constructor</overloads>
		/// <summary>Default constructor</summary>
		public x_worknotify() {
			intialise();
		}
		/// <summary>Sets the type of message (text or html)</summary>
		/// <param name="isHtml">true if message is to be html</param>
		public x_worknotify(bool isHtml) {
			//log4net.Config.XmlConfigurator.Configure();
			html = isHtml;
			intialise();
		}
		#endregion

		#region Public methods
		/// <overloads>Notifies a person by sending a message</overloads>
		/// <summary>
		/// Notifies a user, identified by their GateKeeper ID
		/// </summary>
		/// <param name="UserID">The user's gatekeeper identifier</param>
		/// <param name="Message">The message to be sent to the user</param>
		public void Notify(int UserID, string Message) {
			x_workflow workflowx = new x_workflow();
			XmlElement user = workflowx.GetUser(UserID);
			string useremail = user.SelectSingleNode("EMail").InnerText;
			//string username = String.Concat(user.SelectSingleNode("FirstName").InnerText, " ", user.SelectSingleNode("Surname").InnerText);
			sendEmail(useremail, "", Message);
		}
		/// <summary>
		/// Notifies a user, identified by their GateKeeper ID
		/// </summary>
		/// <param name="UserID">The user's gatekeeper identifier</param>
		/// <param name="Subject">The subject to be sent to the user</param>
		/// <param name="Message">The message to be sent to the user</param>
		public void Notify(int UserID, string Subject, string Message) {
			x_workflow workflowx = new x_workflow();
			XmlElement user = workflowx.GetUser(UserID);
			string useremail = user.SelectSingleNode("//User/EMail").InnerText;
			sendEmail(useremail, Subject, Message);
		}
		/// <summary>
		/// Notifies a user, identified by their GateKeeper ID
		/// </summary>
		/// <param name="UserID">The user's gatekeeper identifier</param>
		/// <param name="isAgent">Flag to indicate agent (gets from Agents table, else GateKeeper)</param>
		/// <param name="Subject">The subject to be sent to the user</param>
		/// <param name="Message">The message to be sent to the user</param>
		/// <param name="AgentDSN">The DSN for the database holding the agent table</param>
		public void Notify(int UserID, bool isAgent, string Subject, string Message, string AgentDSN) {
			string useremail = "";
			if (isAgent) {
				x_workprocess workprocessx = new x_workprocess(AgentDSN);
				XmlElement user = workprocessx.GetAgentXml(UserID);
				if (user.SelectSingleNode("EMail") != null){ // SS 20070530 - legacy not sure why it reads EMail with capital M but in the xml it's Email with small M hence the code below
					useremail = user.SelectSingleNode("EMail").InnerText;
				}else if (user.SelectSingleNode("Email") != null){
					useremail = user.SelectSingleNode("Email").InnerText;
				}
			} else {
				x_workflow workflowx = new x_workflow();
				XmlElement user = workflowx.GetUser(UserID);
				if (user.SelectSingleNode("//agent/Email") != null)
					useremail = user.SelectSingleNode("//agent/Email").InnerText;
			}
			//Logger.Info(useremail);
			sendEmail(useremail, "", Message);
		}
		/// <summary>
		/// Notifies a user with a given name and email address.
		/// </summary>
		/// <param name="UserName">The user's full name</param>
		/// <param name="UserEmail">The user's email address</param>
		/// <param name="Message">The message to be sent to the user</param>
		public void Notify(string UserName, string UserEmail, string Message) {
			sendEmail(UserEmail, UserName, Message);
		}
		/// <summary>
		/// Notifies a user with a given name, email address and contact number.
		/// </summary>
		/// <param name="UserName">The user's full name</param>
		/// <param name="UserEmail">The user's email address</param>
		/// <param name="UserContact">The user's contact number</param>
		/// <param name="Subject">The subject of the message to be sent to the user</param>
		/// <param name="Message">The message to be sent to the user</param>
		public void Notify(string UserName, string UserEmail, string UserContact, string Subject, string Message) {
			if (UserEmail != null && UserEmail != "")
				sendEmail(UserEmail, Subject, Message);
			if (UserContact != null && UserContact != "")
				sendSMS(UserContact, UserName, Message);
		}
		#endregion
		
		#region Protected methods
		/// <summary>
		/// Description of this method
		/// </summary>
		protected void _Example() {
		}
		#endregion
				
		#region Private methods
		/// <summary>
		/// Initialise the properties of the class
		/// </summary>
		private void intialise() {
		}
		/// <summary>
		/// Does the sending of an email.
		/// </summary>
		private void sendEmail(string useremail, string subject, string message) {
			if (html)
				sendHtmlEmail(useremail, subject, message);
			else
				sendTextEmail(useremail, subject, message);
		}
		private void sendTextEmail(string useremail, string subject, string message) {
			try {
				if (useremail == "" || useremail == null)
					throw new Exception(String.Concat("email address empty"));
				x_email emailx = new x_email();
				string from = System.Configuration.ConfigurationManager.AppSettings["notify_from"];
				string subj = String.Concat(System.Configuration.ConfigurationManager.AppSettings["notify_subject"], subject);
				emailx.ToCheck = useremail;
				emailx.From = from;
				emailx.Subject = subj;
				emailx.SendRaw(message);
				//emailx.SendRaw(useremail, from, subj, message);
			} catch(System.Exception e) {
				throw(new x_exception("error_email", String.Concat(error_email, "(", e.Message, ")")));
			}
		}
		private void sendHtmlEmail(string useremail, string subject, string message) {
			try {

                SmtpClient mail = new SmtpClient();
                //mail.DeliveryMethod = mtpDeliveryMethod.Network;
                //mail.UseDefaultCredentials = false;
                //mail.Host = SMTPServer;
                string body = String.Concat(html_header, message, html_footer);
                MailAddress sender = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["notify_from"]);
                MailMessage mailMessage = new MailMessage();

                mailMessage.From = sender;
                mailMessage.To.Add(useremail);
                mailMessage.Body = body;
                mailMessage.IsBodyHtml = true;
                mailMessage.Subject = String.Concat(System.Configuration.ConfigurationManager.AppSettings["notify_subject"], " - ", subject);

                mail.Send(mailMessage);
                /*.net 1.1 compatible code - System.Web.Mail dropped in favour of System.Net.Mail
                MailMessage thismail = new MailMessage();
                thismail.Subject = String.Concat(System.Configuration.ConfigurationManager.AppSettings["notify_subject"], " - ", subject);
                thismail.From = System.Configuration.ConfigurationManager.AppSettings["notify_from"];
                thismail.To = useremail;
                thismail.BodyFormat = MailFormat.Html;
                thismail.Body = String.Concat(html_header, message, html_footer);
                if (System.Configuration.ConfigurationManager.AppSettings["notify_bcc"] != null)
                    thismail.Bcc = System.Configuration.ConfigurationManager.AppSettings["notify_bcc"];
                if (System.Configuration.ConfigurationManager.AppSettings["notify_server"] != null)
                    SmtpMail.SmtpServer = System.Configuration.ConfigurationManager.AppSettings["notify_server"];
                SmtpMail.Send(thismail);
                */
			} catch(System.Exception e) {
				throw(new x_exception("error_email", String.Concat(error_email, "(", e.Message, ")")));
			}
		}
		private void sendSMS(string cellno, string name, string message) {
			NashuaMobile.GKMessage thismsg = new NashuaMobile.GKMessage(System.Configuration.ConfigurationManager.AppSettings["GateKeeperDSN"]);
			string msgtext = (name != "" && name != null)? String.Concat(name, ", ", message) : message;
			if (!thismsg.SendSMS(cellno, msgtext))
				throw new Exception("Could not send message.");
		}
		
		#endregion
	}
}
